package drummer.server;

/**
 *
 * @author Administrator
 */

import java.awt.Component;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import pcserver.MainFrame;

public class DrummerServer {

	private static ServerSocket serverSocket;
	private List<CommandReceiver> receivers = new ArrayList<CommandReceiver>();
	private boolean stopped;
	private int limit = 1;
	private static DrummerServer server = null;
	private MainFrame frame = new MainFrame();	
	
	public static void main(String[] args) {
		
		DrummerServer server = DrummerServer.getInstance();
		try {
			server.startService(54321);
		} catch (IOException e) {
			e.printStackTrace();
		}
		server.getFrame().setLocation(100, 100);
	}

	private Component getFrame() {
		return this.frame;
	}

	private DrummerServer() {
	}

	public void startService(int port) throws IOException {
		serverSocket = new ServerSocket(port);
		while (!this.stopped) {
			while (this.receivers.size() < getLimit()) {
				System.out.println("1:" + this.receivers.size());
				Socket socket = serverSocket.accept();
				System.out.println("accepted:\n\t"
						+ socket.getInetAddress().getHostAddress());
				initReceiver(socket);
			}
			try {
				Thread.sleep(1000);
				System.out.println("waiting……");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void initReceiver(Socket socket) throws IOException {
		CommandReceiver receiver = new CommandReceiver(socket);

		/*** instantiate the handler here ***/
		CommandHandler handler = this.frame.getReceiverHandler();
		/*** **************************** ***/

		receiver.addHandler(handler);
		System.out.println("2:" + this.receivers.size());
		this.receivers.add(receiver);
		System.out.println("2:" + this.receivers.size());
		receiver.start();
	}

	public void stop() throws IOException {
		this.stopped = true;
		for (CommandReceiver r : this.getReceivers()) {
			r.stopReceive();
		}
	}

	public boolean isStopped() {
		return stopped;
	}

	public List<CommandReceiver> getReceivers() {
		return receivers;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public static DrummerServer getInstance() {
		if (server == null)
			server = new DrummerServer();
		return server;
	}

	public void remove(CommandReceiver commandReceiver) {
		System.out.println("size:" + this.receivers.size());
		this.receivers.remove(commandReceiver);
		System.out.println("size:" + this.receivers.size());
	}
}
